// my/pages/Setting/Setting.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 学科数据
    subjects: [
      {
        id: 'physics',
        name: '物理',
        icon: '⚛️',
        color: '#FF6B6B',
        enabled: true,
        description: '力学、电磁学、光学等'
      },
      {
        id: 'chemistry',
        name: '化学',
        icon: '🧪',
        color: '#4ECDC4',
        enabled: true,
        description: '有机化学、无机化学、分析化学'
      },
      {
        id: 'biology',
        name: '生物',
        icon: '🧬',
        color: '#45B7D1',
        enabled: true,
        description: '细胞生物学、遗传学、生态学'
      },
      {
        id: 'politics',
        name: '政治',
        icon: '📚',
        color: '#96CEB4',
        enabled: true,
        description: '政治学、经济学、哲学'
      }
    ],
    
    // 设置项数据
    settings: {
      // 学科设置
      physicsReminder: true,
      chemistryDifficulty: '中等',
      biologyMode: '标准模式',
      politicsPush: true,
      
      // 通用设置
      generalNotification: true,
      darkMode: false
    },
    
    // 难度选项
    difficultyOptions: ['简单', '中等', '困难', '专家'],
    
    // 练习模式选项
    practiceModes: ['标准模式', '快速练习', '深度学习', '模拟考试']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadSettings();
    this.loadSubjectStatus();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.setNavigationBarStyle();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.refreshSettings();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.saveSettings();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.saveSettings();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshSettings();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 可以加载更多设置项
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '学科设置 - 个性化你的学习体验',
      path: '/pages/Setting/Setting'
    };
  },

  /**
   * 加载设置数据
   */
  loadSettings() {
    try {
      const savedSettings = wx.getStorageSync('subjectSettings');
      if (savedSettings) {
        this.setData({
          settings: { ...this.data.settings, ...savedSettings }
        });
      }
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  },

  /**
   * 加载学科状态
   */
  loadSubjectStatus() {
    try {
      const subjectStatus = wx.getStorageSync('subjectStatus');
      if (subjectStatus) {
        const subjects = this.data.subjects.map(subject => {
          const status = subjectStatus[subject.id];
          return {
            ...subject,
            enabled: status !== undefined ? status : subject.enabled
          };
        });
        this.setData({ subjects });
      }
    } catch (error) {
      console.error('加载学科状态失败:', error);
    }
  },

  /**
   * 保存设置数据
   */
  saveSettings() {
    try {
      wx.setStorageSync('subjectSettings', this.data.settings);
      
      const subjectStatus = {};
      this.data.subjects.forEach(subject => {
        subjectStatus[subject.id] = subject.enabled;
      });
      wx.setStorageSync('subjectStatus', subjectStatus);
    } catch (error) {
      console.error('保存设置失败:', error);
    }
  },

  /**
   * 刷新设置
   */
  refreshSettings() {
    this.loadSettings();
    this.loadSubjectStatus();
    wx.showToast({
      title: '设置已刷新',
      icon: 'success',
      duration: 1000
    });
  },

  /**
   * 选择学科
   */
  selectSubject(e) {
    const subjectId = e.currentTarget.dataset.subject;
    const subjects = this.data.subjects.map(subject => {
      if (subject.id === subjectId) {
        return { ...subject, enabled: !subject.enabled };
      }
      return subject;
    });
    
    this.setData({ subjects });
    this.saveSettings();
    
    const subject = subjects.find(s => s.id === subjectId);
    wx.showToast({
      title: subject.enabled ? `${subject.name}已启用` : `${subject.name}已禁用`,
      icon: 'success'
    });
  },

  /**
   * 切换设置项
   */
  toggleSetting(e) {
    const setting = e.currentTarget.dataset.setting;
    const settings = { ...this.data.settings };
    settings[setting] = e.detail.value;
    
    this.setData({ settings });
    this.saveSettings();
    
    // 显示设置变更提示
    const settingNames = {
      physicsReminder: '物理学习提醒',
      politicsPush: '政治知识点推送',
      generalNotification: '通知设置',
      darkMode: '深色模式'
    };
    
    wx.showToast({
      title: `${settingNames[setting]}已${settings[setting] ? '开启' : '关闭'}`,
      icon: 'success'
    });
  },

  /**
   * 显示难度选项
   */
  showDifficultyOptions() {
    wx.showActionSheet({
      itemList: this.data.difficultyOptions,
      success: (res) => {
        const selectedDifficulty = this.data.difficultyOptions[res.tapIndex];
        const settings = { ...this.data.settings };
        settings.chemistryDifficulty = selectedDifficulty;
        
        this.setData({ settings });
        this.saveSettings();
        
        wx.showToast({
          title: `化学难度已设置为${selectedDifficulty}`,
          icon: 'success'
        });
      }
    });
  },

  /**
   * 显示练习模式选项
   */
  showPracticeModes() {
    wx.showActionSheet({
      itemList: this.data.practiceModes,
      success: (res) => {
        const selectedMode = this.data.practiceModes[res.tapIndex];
        const settings = { ...this.data.settings };
        settings.biologyMode = selectedMode;
        
        this.setData({ settings });
        this.saveSettings();
        
        wx.showToast({
          title: `生物练习模式已设置为${selectedMode}`,
          icon: 'success'
        });
      }
    });
  },

  /**
   * 设置导航栏样式
   */
  setNavigationBarStyle() {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#667eea'
    });
  },

    /**
   * 退出登录
   */
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 停止token过期检测服务
          this.stopTokenCheckService();
          
          // 清除用户数据
          try {
            const { removeAuthData } = require('../../../utils/storageUtil.js');
            removeAuthData();
            
            wx.showToast({
              title: '已退出登录',
              icon: 'success',
              duration: 1500,
              success: () => {
                setTimeout(() => {
                  wx.reLaunch({
                    url: '/my/pages/Login/Login'
                  });
                }, 1500);
              }
            });
          } catch (error) {
            console.error('退出登录失败:', error);
            wx.showToast({
              title: '退出登录失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  /**
   * 停止token过期检测服务
   */
  stopTokenCheckService() {
    try {
      const { tokenService } = require('../../../utils/tokenService.js');
      if (tokenService) {
        console.log('用户主动登出，停止token过期检测服务');
        tokenService.stopTokenCheck();
      }
    } catch (error) {
      console.error('停止token检测服务失败:', error);
    }
  }
})